package icu.javayanglei.controller.wallpaper.controller;

import cn.hutool.core.lang.Validator;
import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import icu.javayanglei.annotation.ResponseResult;
import icu.javayanglei.entity.Wallpaper;
import icu.javayanglei.enumeration.ResultCode;
import icu.javayanglei.exception.ResultException;
import icu.javayanglei.service.IWallpaperService;
import icu.javayanglei.util.fastdfs.FastdfsUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;

/**
 * 壁纸 控制层
 *
 * @author yang
 * @version 1.0.0
 * @date 2020-11-22 10:50
 */
@RestController
@ResponseResult
@RequestMapping("/api/wallpaper")
@Slf4j
public class WallpaperController {
    @Autowired
    private IWallpaperService iWallpaperService;

    @Autowired
    private FastdfsUtil fastdfsUtil;

    @GetMapping("/hello")
    public String hello() {
        return "hello";
    }

    /**
     * 分页获取所有的壁纸
     *
     * @param pageNumber 第几页
     * @param pageSize   每页几条
     * @return 分页 page
     */
    @GetMapping("/getAll")
    public Page<Wallpaper> getAll(String pageNumber, Integer pageSize) {
        int page;
        String nan = "NaN";
        if (nan.equals(pageNumber) || ObjectUtil.isNull(pageNumber)) {
            page = 1;
        } else {
            page = Integer.parseInt(pageNumber);
        }
        Page<Wallpaper> objectPage = new Page<>(page, pageSize);
        return iWallpaperService.page(objectPage);
    }

    @GetMapping("/download/{id}")
    public void downloadMethod(@PathVariable("id") Integer did, HttpServletResponse response, HttpServletRequest request) throws IOException {
        log.debug(" did = {}", did);
        // 获取文件对象
        final Wallpaper byId = iWallpaperService.getById(did);
        if (Validator.isNull(byId)) {
            throw new ResultException(ResultCode.SERVER_NO_SUCH_ID);
        }
        // 获取文件名字
        final String fileName = byId.getName();
        log.debug(" file name = {}", fileName);

        response.reset();
        response.setCharacterEncoding("utf-8");
        response.setContentType("application/x-download");
        response.addHeader("Content-Disposition", "attachment;filename=" + encodeFileName(request, fileName));
        fastdfsUtil.download(byId.getRemoteUrl(), response.getOutputStream());
        response.addHeader("Content-Length", byId.getSize());
        response.setContentType("application/octet-stream;charset=UTF-8");
    }

    /**
     * 下载文件名中含有中文的处理
     *
     * @param req      域
     * @param headName 文件名
     * @return 转码后的文件名
     */
    private String encodeFileName(HttpServletRequest req, String headName)
            throws UnsupportedEncodingException {
        //IE9之前包括IE9都包含MSIE;IE10之后都包含Trident;edge浏览器包含Edge
        String msie = "MSIE";
        String trident = "Trident";
        String edge = "Edge";
        String filename = "";
        String userAgent = req.getHeader("User-Agent");
        if (userAgent.contains(msie) || userAgent.contains(trident) || userAgent.contains(edge)) {
            filename = URLEncoder.encode(headName, String.valueOf(StandardCharsets.UTF_8));

        } else {
            filename = new String(headName.getBytes(StandardCharsets.UTF_8), StandardCharsets.ISO_8859_1);
        }
        return filename;
    }

}
